package com.psa.processor;

import android.app.Activity;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;
import com.psa.tool.*;
import com.wxw.BaseLibrary.element.JsonObject;
import com.wxw.BaseLibrary.element.JsonProperty;
import com.wxw.BaseLibrary.element.JsonPropertyType;
import org.apache.http.Header;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author david
 */
public class ErrorLogUploadProcessor {
    private Activity parentActivity = null;
    private IGeneralEventCallback generalEventCallback;
    private RequestParams params;
    private SyncHttpClient client = new SyncHttpClient();
    private boolean uploading = false;
    private boolean running = false;
    private JsonProperty returnMsg = new JsonProperty();
    private String errorType = "error";
    private boolean deleteFile = true;
    private String filePath = SystemStatus.APP_PATH + errorType;
    private List<File> uploadedList = new ArrayList<>();

    public ErrorLogUploadProcessor(Activity activity) {
        parentActivity = activity;
    }

    public ErrorLogUploadProcessor(Activity activity, String errorType) {
        parentActivity = activity;
        this.errorType = errorType;
        filePath = SystemStatus.APP_PATH + errorType;
    }

    public boolean isDeleteFile() {
        return deleteFile;
    }

    public void setDeleteFile(boolean deleteFile) {
        this.deleteFile = deleteFile;
    }

    private Thread sendThread = new Thread(new Runnable() {
        @Override
        public void run() {
            running = true;
            try {
                JsonObject json = new JsonObject();
                json.setProperty("UserID", new JsonProperty("'" + SystemStatus.currentUser.getCorp() + "-" + SystemStatus.currentUser.getId() + "-" + SystemStatus.currentUser.getName() + "'"));
                json.setProperty("Phone", new JsonProperty("'" + PhoneState.getPhoneState(PHONE_STATE.DeviceId, parentActivity).toString() + "'"));
                json.setProperty("path", new JsonProperty(errorType));
                try {
                    File file = new File(filePath);
                    if (file.isDirectory() && file.listFiles().length > 0) {
                        for (File f : file.listFiles()) {
                            if (f.isFile() && f.exists()) {
                                params = new RequestParams();
                                json.setProperty("fname", new JsonProperty(f.getName()));
                                params.put("info", json.toString());
                                params.put("file", f);
                                doUpload();
                                uploadedList.add(f);
                            }
                            while (uploading) {
                                Thread.sleep(1000);
                            }
                            if (!running) {
                                client.cancelAllRequests(true);
                                break;
                            }
                        }
                        if (deleteFile && uploadedList.size() > 0) {
                            for (File f : uploadedList) {
                                f.delete();
                            }
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                if (returnMsg.getType() == JsonPropertyType.Array && returnMsg.getItems().size() > 0) {
                    event(returnMsg.toString());
                }
            } catch (Exception e) {
                event("上传错误日志异常:" + e.getMessage());
            }
        }
    });

    private void doUpload() {
        uploading = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                client.post(SystemStatus.LOGIN_URL + "/uploadErrLogFile", params,
                        new AsyncHttpResponseHandler() {
                            @Override
                            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                                String s = "";
                                if (bytes != null && bytes.length > 0) {
                                    s = new String(bytes);
                                    s = SystemTool.getHttpResponseContent(s);
                                } else {
                                    s = "连接服务器超时，服务器当前无法连接！";
                                }
                                JsonObject j = new JsonObject();
                                j.setProperty("upload_error", new JsonProperty(s));
                                returnMsg.add(j);
                                uploading = false;
                            }

                            @Override
                            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                                String s = new String(bytes);
                                s = SystemTool.getHttpResponseContent(s);
                                try {
                                    returnMsg.add(new JsonObject(s));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                uploading = false;
                            }

                            @Override
                            public void onProgress(long bytesWritten, long totalSize) {
                                super.onProgress(bytesWritten, totalSize);
                            }
                        });
            }
        }).start();
    }

    private void event(String ev){
        if (ev != null && !ev.equals("") && !ev.toLowerCase().equals("null")) {
            SystemStatus.addMessage(ev);
        }
        if (generalEventCallback!=null) {
            generalEventCallback.finished(this, ev);
        }
    }

    public void doStart() {
        if (sendThread != null) {
            sendThread.start();
        }
    }

    public void setGeneralEventCallback(IGeneralEventCallback generalEventCallback) {
        this.generalEventCallback = generalEventCallback;
    }

    public void stop() {
        running = false;
        uploading = false;
    }
}
